import 'package:flutter/material.dart';
import 'package:flutter_base/base/pop_base_state.dart';
import 'package:flutter_base/common/user_helper.dart';
import 'package:flutter_base/page/common/common_dialog.dart';
import 'package:flutter_base/page/login/login_page.dart';
import 'package:flutter_base/page/mine/about_us_page.dart';
import 'package:flutter_base/page/mine/collect_page.dart';
import 'package:flutter_base/utils/navigator_utils.dart';
import 'package:flutter_base/utils/toast_utils.dart';
import 'package:flutter_base/viewmodel/login/login_vm.dart';
import 'package:flutter_base/viewmodel/mine/mine_vm.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

///
/// @DIR_PATH：lib/page/mine
/// @TIME：2023/11/12 15:42
/// @AUTHOR：starr.
/// @DESC：我的页面
///
class MinePage extends StatefulWidget {
  const MinePage({super.key});

  @override
  State<StatefulWidget> createState() => _MinePageState();
}

class _MinePageState extends PopBaseState<MinePage>
    with SingleTickerProviderStateMixin {
  late List<Widget> list;
  late TabController _tabController;
  MineViewModel viewModel =MineViewModel();

  List<String> titles = ["我的收藏", "检查更新", "关于我们"];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _tabController.addListener(() {
      ToastUtils.showToast("当前选中的是${_tabController.index}");
    });

    if (UserHelper.getInstance.userIsLogin) {
      LoginViewModel viewModel = LoginViewModel();
      //注册成功回到登录页面
      viewModel.registerInfo.name = "starry陆离";
      viewModel.registerInfo.password = "lxloveth0411";
      viewModel.login().then((value) {
        if (value == true) {
          showToast("登录成功");
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(create: (context){
      return viewModel;
    },child:
    Scaffold(
      body: Consumer(builder: (context,vm,child){
        return CustomScrollView(
          slivers: <Widget>[
            SliverAppBar(
              title: Row(
                children: [
                  ClipRRect(
                    borderRadius: const BorderRadius.all(Radius.circular(30)),
                    child: Image.asset("assets/images/a/ic_app.png",
                        width: 50, height: 50, fit: BoxFit.fill),
                  ),
                  Text(
                      (UserHelper.getInstance.userIsLogin == false)
                          ? "未登录"
                          : UserHelper.getInstance.userBean?.username
                          .toString() ??
                          "默认用户",
                      style: const TextStyle(
                          fontSize: 18, color: Colors.black)),
                ],
              ),
              flexibleSpace: const FlexibleSpaceBar(
                  centerTitle: true, collapseMode: CollapseMode.pin),
              backgroundColor: Colors.blue,
              expandedHeight: 200,
              floating: true,
              pinned: true,
              //固定
              snap: true,
              actions: <Widget>[
                IconButton(
                  onPressed: () {
                    ToastUtils.showToast("更多");
                  },
                  icon: const Icon(Icons.more_horiz),
                ),
              ],
            ),
            SliverList(
              delegate: SliverChildBuilderDelegate(
                      (BuildContext context, int index) {
                  return _itemWidgetDefault(context, () {
                    if (index == 0) {
                      NavigatorUtils.pushPage(context, CollectPage());
                    } else if (index == 2) {
                      NavigatorUtils.pushPage(context, AboutUsPage());
                    }else{
                      viewModel.checkAppUpdate().then((url){
                        if(url!=null && url.isNotEmpty==true){
                          showCommonAlertDialog(context: context,
                          selectText: "更新",
                          cancleText: "取消", contentMessag:"检查到有新版本!",
                          selectCallBack: (){
                            viewModel.jumpToOutLink(url);
                          });
                        }else{
                          showToast("当前已经是最新版本");
                        }
                      });

                    }
                  }, Icons.account_circle, titles[index],
                      Icons.arrow_forward_ios);
                }, childCount: titles.length),
              ),
              SliverToBoxAdapter(
              child: Container(
                height: 50,
                margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
                padding: const EdgeInsets.symmetric(horizontal: 10),
                decoration: BoxDecoration(
                    borderRadius: const BorderRadius.all(Radius.circular(10)),
                    border: Border.all(color: Colors.grey, width: 0.5)),
                child: TextButton(
                  onPressed: () {
                    loginOrExit();
                  },
                  child: Text((UserHelper.getInstance.userIsLogin == false)
                      ? "登录"
                      : "退出登录",
                      style: const TextStyle(
                          fontSize: 18, color: Colors.deepOrangeAccent)),
                ),
              ),
            ),
            SliverToBoxAdapter(
              child:  GestureDetector(
                child: Container(
                  width: 30,
                  margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
                  padding: const EdgeInsets.symmetric(horizontal: 10),
                  child: Text((UserHelper.getInstance.userIsLogin == false) ? "快捷登录" : "", textAlign: TextAlign.center,
                      style: const TextStyle(
                          fontSize: 18, color: Colors.grey,))
                  ),
                onTap: (){
                  LoginViewModel viewModel =LoginViewModel();
                  //注册成功回到登录页面
                  viewModel.registerInfo.name="starry陆离";
                  viewModel.registerInfo.password = "lxloveth0411";
                  viewModel.login().then((value) {
                    if(value == true){
                      showToast("登录成功");
                    }
                  });
                },
              ),
            )
          ],
        );
      }),
    ),);
  }

  Widget _itemWidgetDefault(BuildContext context, GestureTapCallback onTap,
      IconData leftIcon, String title, IconData rightIcon) {
    return InkWell(
      onTap: onTap,
      child: Container(
        height: 50,
        margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
        padding: const EdgeInsets.symmetric(horizontal: 10),
        decoration: BoxDecoration(
            borderRadius: const BorderRadius.all(Radius.circular(10)),
            border: Border.all(color: Colors.grey, width: 0.5)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Icon(leftIcon, size: 20),
            const SizedBox(width: 20),
            Expanded(
                child: Text(
              title,
              style: Theme.of(context).textTheme.titleSmall,
            )),
            Icon(
              rightIcon,
              size: 18,
            ),
          ],
        ),
      ),
    );
  }

  void loginOrExit() {
    if (UserHelper.getInstance.userIsLogin) {
      viewModel.exitLogin((value) {
        if(value){
          showToast("退出登录");
          NavigatorUtils.openPageByFade(context, const BobbleLoginPage(),
              isReplace: true);
        }
      });
    } else {
      NavigatorUtils.openPageByFade(context, const BobbleLoginPage(),
          isReplace: false);
    }
  }
}
